package com.gitee.cui.server.processor;

import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import com.gitee.cui.common.util.Logger;
import com.gitee.cui.server.server.ServerSession;
import com.gitee.cui.server.server.SessionMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/28 9:43
 **/
@Slf4j
@Service
public class ChatRedirectProcessor extends AbstractServerProcessor {
    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.MESSAGE_REQUEST;
    }

    @Override
    public boolean action(ServerSession session, ProtoMsg.Message message) {
        ProtoMsg.MessageRequest msg = message.getMessageRequest();
        Logger.tcfo("chatMsg | from= " + msg.getFrom() +" , to= " + msg.getTo() + " , content= " + msg.getContent());
        String uid = msg.getTo();
        List<ServerSession> sessionList = SessionMap.inst().getSessionsByUid(uid);

        if (CollectionUtils.isEmpty(sessionList)) {
            Logger.tcfo("[" + uid + "]不在线，发送失败！");
            return false;
        } else {
            sessionList.forEach(sess -> {
                sess.writeAndFlush(message);
            });
        }
        return true;
    }
}
